%% 智能连接SVG模型 - 基于端口类型匹配
function smart_connect_svg(model_name)
    % 默认模型名
    if nargin < 1
        model_name = 'SVG_Star_10kV_Complete';
    end
    
    % 确保模型已打开
    if ~bdIsLoaded(model_name)
        open_system(model_name);
    end
    
    fprintf('开始智能连接子系统...\n');
    
    %% 1. 分析模型中的所有模块和端口
    fprintf('分析模型结构...\n');
    blocks = find_system(model_name, 'SearchDepth', 1, 'Type', 'Block');
    
    % 存储模块信息
    block_info = struct();
    
    for i = 1:length(blocks)
        block_path = blocks{i};
        if strcmp(block_path, model_name)
            continue; % 跳过模型本身
        end
        
        block_name = get_param(block_path, 'Name');
        block_type = get_param(block_path, 'BlockType');
        
        % 获取端口信息
        try
            port_handles = get_param(block_path, 'PortHandles');
            port_types = get_param(block_path, 'PortTypes');
            
            % 对于电力系统模块，端口类型可能不同
            if isfield(port_handles, 'LConn') || isfield(port_handles, 'RConn')
                % 电力系统连接端口
                block_info.(block_name).type = 'Power';
                block_info.(block_name).block_type = block_type;
                block_info.(block_name).path = block_path;
                block_info.(block_name).ports = port_handles;
                
                % 计算端口数量
                n_left = 0;
                n_right = 0;
                if isfield(port_handles, 'LConn')
                    n_left = length(port_handles.LConn);
                end
                if isfield(port_handles, 'RConn')
                    n_right = length(port_handles.RConn);
                end
                block_info.(block_name).n_ports = [n_left, n_right];
                
                fprintf('  %s: 电力模块, 左端口=%d, 右端口=%d\n', block_name, n_left, n_right);
            else
                % 控制系统端口
                block_info.(block_name).type = 'Signal';
                block_info.(block_name).block_type = block_type;
                block_info.(block_name).path = block_path;
                block_info.(block_name).ports = port_handles;
                
                % 计算端口数量
                n_in = length(port_handles.Inport);
                n_out = length(port_handles.Outport);
                block_info.(block_name).n_ports = [n_in, n_out];
                
                fprintf('  %s: 信号模块, 输入=%d, 输出=%d\n', block_name, n_in, n_out);
            end
        catch
            fprintf('  %s: 无法获取端口信息\n', block_name);
        end
    end
    
    %% 2. 基于模块类型和名称进行智能连接
    fprintf('\n开始智能连接...\n');
    
    % 2.1 连接电网系统
    connect_grid_system(model_name, block_info);
    
    % 2.2 连接SVG到负载
    connect_svg_to_load(model_name, block_info);
    
    % 2.3 连接测量系统
    connect_measurement_system(model_name, block_info);
    
    % 2.4 连接控制系统
    connect_control_system(model_name, block_info);
    
    % 2.5 连接储能系统
    connect_storage_system(model_name, block_info);
    
    %% 3. 验证连接
    verify_connections(model_name);
    
    fprintf('\n智能连接完成！\n');
end

%% 子函数：连接电网系统
function connect_grid_system(model_name, block_info)
    fprintf('  连接电网系统...\n');
    
    % 查找电源模块
    source_blocks = {};
    impedance_blocks = {};
    
    fields = fieldnames(block_info);
    for i = 1:length(fields)
        block_name = fields{i};
        if contains(block_name, 'Grid') && ~contains(block_name, '_Z')
            if block_info.(block_name).type == 'Power'
                source_blocks{end+1} = block_name;
            end
        elseif contains(block_name, '_Z')
            impedance_blocks{end+1} = block_name;
        end
    end
    
    % 连接电源到阻抗
    for i = 1:length(source_blocks)
        src_name = source_blocks{i};
        % 查找对应的阻抗
        if contains(src_name, 'Strong')
            z_name = 'Strong_Grid_Z';
        elseif contains(src_name, 'Weak')
            z_name = 'Weak_Grid_Z';
        else
            continue;
        end
        
        if isfield(block_info, z_name)
            try
                connect_power_blocks(model_name, src_name, z_name, block_info);
                fprintf('    已连接: %s -> %s\n', src_name, z_name);
            catch ME
                fprintf('    连接失败 %s -> %s: %s\n', src_name, z_name, ME.message);
            end
        end
    end
    
    % 连接阻抗到SVG（如果没有切换开关）
    if ~isfield(block_info, 'Grid_Selector') && isfield(block_info, 'Star_SVG')
        % 直接连接强电网到SVG
        if isfield(block_info, 'Strong_Grid_Z')
            try
                connect_power_blocks(model_name, 'Strong_Grid_Z', 'Star_SVG', block_info);
                fprintf('    已连接: Strong_Grid_Z -> Star_SVG\n');
            catch ME
                fprintf('    连接失败: %s\n', ME.message);
            end
        end
    end
end

%% 子函数：连接SVG到负载
function connect_svg_to_load(model_name, block_info)
    fprintf('  连接SVG到负载...\n');
    
    if isfield(block_info, 'Star_SVG') && isfield(block_info, 'Mixed_Load')
        try
            connect_power_blocks(model_name, 'Star_SVG', 'Mixed_Load', block_info);
            fprintf('    已连接: Star_SVG -> Mixed_Load\n');
        catch ME
            fprintf('    连接失败: %s\n', ME.message);
        end
    end
end

%% 子函数：连接测量系统
function connect_measurement_system(model_name, block_info)
    fprintf('  连接测量系统...\n');
    
    % 这里需要更复杂的逻辑，暂时跳过
    fprintf('    测量系统需要手动连接\n');
end

%% 子函数：连接控制系统
function connect_control_system(model_name, block_info)
    fprintf('  连接控制系统...\n');
    
    % 查找控制输入和输出
    if isfield(block_info, 'Control_System') && block_info.Control_System.type == 'Signal'
        % 连接测量信号到控制系统
        if isfield(block_info, 'Measurements')
            % 需要进入子系统查看具体端口
            fprintf('    控制系统连接需要手动完成\n');
        end
    end
end

%% 子函数：连接储能系统
function connect_storage_system(model_name, block_info)
    fprintf('  连接储能系统...\n');
    
    if isfield(block_info, 'Energy_Storage')
        fprintf('    储能系统连接需要在子系统内部完成\n');
    end
end

%% 辅助函数：连接两个电力模块
function connect_power_blocks(model_name, src_block, dst_block, block_info)
    src_ports = block_info.(src_block).ports;
    dst_ports = block_info.(dst_block).ports;
    
    % 获取源模块的右端口
    if isfield(src_ports, 'RConn') && ~isempty(src_ports.RConn)
        src_port = src_ports.RConn(1);
    else
        error('源模块没有右连接端口');
    end
    
    % 获取目标模块的左端口
    if isfield(dst_ports, 'LConn') && ~isempty(dst_ports.LConn)
        dst_port = dst_ports.LConn(1);
    else
        error('目标模块没有左连接端口');
    end
    
    % 检查是否已经连接
    existing_line = get_param(src_port, 'Line');
    if existing_line == -1
        % 未连接，创建新连接
        add_line(model_name, src_port, dst_port, 'autorouting', 'on');
    else
        % 已连接
        fprintf('      端口已连接\n');
    end
end

%% 辅助函数：验证连接
function verify_connections(model_name)
    fprintf('\n验证连接状态...\n');
    
    % 查找所有未连接的端口
    blocks = find_system(model_name, 'SearchDepth', 1, 'Type', 'Block');
    unconnected_count = 0;
    
    for i = 1:length(blocks)
        block_path = blocks{i};
        if strcmp(block_path, model_name)
            continue;
        end
        
        block_name = get_param(block_path, 'Name');
        
        try
            port_handles = get_param(block_path, 'PortHandles');
            
            % 检查电力端口
            if isfield(port_handles, 'LConn')
                for j = 1:length(port_handles.LConn)
                    if get_param(port_handles.LConn(j), 'Line') == -1
                        fprintf('  警告: %s 左端口%d 未连接\n', block_name, j);
                        unconnected_count = unconnected_count + 1;
                    end
                end
            end
            
            if isfield(port_handles, 'RConn')
                for j = 1:length(port_handles.RConn)
                    if get_param(port_handles.RConn(j), 'Line') == -1
                        fprintf('  警告: %s 右端口%d 未连接\n', block_name, j);
                        unconnected_count = unconnected_count + 1;
                    end
                end
            end
            
            % 检查信号端口
            if isfield(port_handles, 'Inport')
                for j = 1:length(port_handles.Inport)
                    if get_param(port_handles.Inport(j), 'Line') == -1
                        fprintf('  警告: %s 输入端口%d 未连接\n', block_name, j);
                        unconnected_count = unconnected_count + 1;
                    end
                end
            end
            
            if isfield(port_handles, 'Outport')
                for j = 1:length(port_handles.Outport)
                    if get_param(port_handles.Outport(j), 'Line') == -1 && ~contains(block_name, 'Scope')
                        fprintf('  警告: %s 输出端口%d 未连接\n', block_name, j);
                        unconnected_count = unconnected_count + 1;
                    end
                end
            end
        catch
            % 忽略错误
        end
    end
    
    if unconnected_count == 0
        fprintf('  所有端口都已连接！\n');
    else
        fprintf('  共有 %d 个端口未连接\n', unconnected_count);
    end
end